<template>
	<div class="cif-model">
		<div class="cif-model-label">{{ props.data.displayName }}</div>
		<div class="cif-model-wrapper">
			<chunk-uploader
				ref="uploadRef"
				:accept="acceptFileType"
				:disabled="loading"
				:value="value"
				:engine-percentages="enginePercentages"
				@file-change="handleFileChange"
				@upload-success="uploadSuccess"
				@upload-error="uploadError"
				@line-change="lineChange"
				:fileBlockSize="5 * 1024 * 1024">
				<template #default>
					<el-button type="primary" size="small">大文件上传</el-button>
				</template>
			</chunk-uploader>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, ref, inject, watch, computed } from 'vue';
import { findConfigDataByName } from '@CIF/Utils/reduce-config';
import _ from 'lodash';
import ChunkUploader from './chunk-upload/index.vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import useClipboard from 'vue-clipboard3';
import acceptFileType from './chunk-upload/accept-file-types.json';
import { getLocalstorage } from '@/utils/localstorage';

const { toClipboard } = useClipboard();
const configuration: any = inject('configuration');
const props = defineProps({
	data: {
		type: Object,
		default() {
			return {};
		}
	}, // cpntTreeNode
	arrayName: String,
	childName: String
});

const ERROR_TYPE: any = {
	1: '预检期发生错误',
	2: '文件上传过程发生错误',
	3: '文件合并时发生错误',
	4: '其它'
};
const emit = defineEmits(['handleValueChange']);
const uploadRef = ref<any>(null);
const enginePercentages = ref<boolean[]>([]);
const loading = ref(false);
const value = ref(props.data.value);
const name = ref('');
const size: any = ref(0);
const unUpload = ref(true);
const config = ref(props.data.config || {});
const e9y = ref({ e9y: '' });
const accessToken = getLocalstorage('access_token');
const url = ref(import.meta.env?.VITE_APP_UPLOAD_API || '/api/sys-storage/upload');
const acceptList = computed(() => {
	return props.data.config.accept || '';
});
// watch(
// 	() => props.data,
// 	(nv) => {
// 		value.value = nv.value;
// 		if (nv.value) {
// 			axios({
// 				method: 'get',
// 				url: '/sys-storage/download',
// 				params: {
// 					f8s: nv.value
// 				}
// 			}).then((r: any) => {
// 				const fileInfo = _.get(r, 'data[0]', {});
// 				name.value = fileInfo.fileName;
// 				size.value = formatFileSize(fileInfo.size);
// 			});
// 		}
// 	},
// 	{ deep: true, immediate: true }
// );
//格式化文件大小
function formatFileSize(value: any) {
	if (value == null || value == '' || value == '0') {
		return '-';
	}
	const unitArr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	let index = 0;
	const srcsize = parseFloat(value);
	index = Math.floor(Math.log(srcsize) / Math.log(1024));
	let size: any = srcsize / Math.pow(1024, index);
	size = size.toFixed(2); // 保留的小数位数
	return size + unitArr[index];
}

function removeOldFile() {
	unUpload.value = false;
	handleChange('');
}
function handleBeforeUpload(file: any) {
	unUpload.value = false;
	return true;
}
function handleFileChange(fileItemList: any) {
	console.log('CIF.CC.CCT.C.Model:fileItemList', fileItemList);
	loading.value = true;
	uploadRef.value.submit();
	// let c = typeof configuration === 'function' ? configuration() : configuration;
	// if (props.arrayName) {
	// 	let data = findConfigDataByName(c, props.arrayName);
	// 	data = findConfigDataByName(data.value, props.childName);
	// 	data = findConfigDataByName(data.value, props.data.name);
	// 	data.value = fileItemList[0];
	// } else {
	// 	let data = findConfigDataByName(c, props.data.name);
	// 	data.value = fileItemList[0];
	// }
	// // 触发值变动通知
	// emit('handleValueChange');
}
function handleChange(groupToken: any) {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log('CIF.CC.CCT.C.Model:handleChange 值发生变更', groupToken);
		let c = typeof configuration === 'function' ? configuration() : configuration;
		if (props.arrayName) {
			let data = findConfigDataByName(c, props.arrayName);
			data = findConfigDataByName(data.value, props.childName);
			data = findConfigDataByName(data.value, props.data.name);
			data.value = groupToken;
		} else {
			let data = findConfigDataByName(c, props.data.name);
			data.value = groupToken;
		}
		// 触发值变动通知
		emit('handleValueChange');
	}
}
function lineChange(status: any) {
	status ? ElMessage('当前连接状态正常') : ElMessage.error('当前连接状态异常');
}
function uploadError(type: any, fileObj: any, error: any) {
	if (error) {
		if (typeof error === 'string') {
			ElMessage.error(`大文件上传失败, 原因：${ERROR_TYPE[type]}, ${error}`);
		} else if (error.message && typeof error.message === 'string') {
			ElMessage.error(`大文件上传失败, 原因：${ERROR_TYPE[type]}, ${error.message}`);
		}
	}
}
function uploadCancel() {
	ElMessage('取消大文件上传成功');
}
//文件上传成功后回调
const uploadSuccess = async (fileObj: any, response: any) => {
	loading.value = false;
	let groupToken;
	if (typeof response === 'string') {
		groupToken = response;
	} else if (typeof response === 'object') {
		groupToken = response.data.groupToken;
	}
	handleChange(groupToken);
	name.value = _.get(fileObj, 'name', '文件名');
	try {
		await toClipboard(groupToken);
		ElMessage.success('大文件groupToken已经被复制到粘贴板');
	} catch (e: any) {
		ElMessage.error('大文件groupToken复制失败', e);
	}
};

onMounted(() => {});
defineExpose({});
</script>

<style lang="scss" scoped>
.cif-model {
	display: flex;
	margin-bottom: 10px;
	justify-content: space-between;

	&-label {
		height: 28px;
		line-height: 28px;
		display: inline-block;
		white-space: nowrap;
		text-align: right;
		vertical-align: middle;
		margin-right: 10px;
	}
	&-wrapper {
		width: calc(100% - 28px);
		.file-card {
			text-align: right;
		}

		.fake-uploader {
			.upload-list {
				margin: 8px 0;
				justify-content: flex-end;
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				padding: 0;
				list-style: none;

				.list-fileObj {
					margin: 0;
					background: var(--primary-active);
					border: none;
					width: 100%;
					height: 59px;
					transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
					font-size: 14px;
					color: var(--white) !important;
					background: var(--primary-active);
					line-height: 1.8;
					position: relative;
					box-sizing: border-box;
					border-radius: 2px;
					max-width: 200px;
					list-style-type: none;

					i {
						color: var(--white) !important;
					}

					.fileObj-a {
						display: flex;
						align-items: center;
						padding: 10px;
						color: var(--white);
						margin-right: 0;
						transition: color 0.3s;
						text-overflow: ellipsis;
						white-space: nowrap;

						.file-name {
							color: var(--white);
						}

						svg {
							font-size: 25px;
							margin-right: 7px;
						}
					}
				}
			}
		}
	}
}
</style>
